package com.dci.intellij.dbn2.browser.ui;

import com.dci.intellij.dbn.browser.options.BrowserDisplayMode;
import com.dci.intellij.dbn.browser.options.DatabaseBrowserSettings;
import com.dci.intellij.dbn.browser.ui.DatabaseBrowserForm;
import com.dci.intellij.dbn.browser.ui.SpySimpleBrowserForm;
import com.dci.intellij.dbn.browser.ui.SpyTabbedBrowserForm;
import com.dci.intellij.dbn.browser.ui.TabbedBrowserForm;
import com.dci.intellij.dbn.common.dispose.Disposer;
import com.dci.intellij.dbn.common.ui.GUIUtil;
import com.dci.intellij.dbn2.utils.ReflectionUtils;
import com.intellij.openapi.project.Project;

import javax.swing.*;

public class BrowserToolWindowForm extends com.dci.intellij.dbn.browser.ui.BrowserToolWindowForm {
    public BrowserToolWindowForm(Project project) {
        super(project);
    }

    @Override
    public void rebuild() {
        setDisplayMode(DatabaseBrowserSettings.getInstance(this.getProject()).getGeneralSettings().getDisplayMode());
        DatabaseBrowserForm oldBrowserForm = getBrowserForm();
        TabbedBrowserForm previousTabbedForm = oldBrowserForm instanceof TabbedBrowserForm ? (TabbedBrowserForm)oldBrowserForm : null;

        DatabaseBrowserForm newBrowserForm = null;
        if (getDisplayMode() == BrowserDisplayMode.TABBED) {
            newBrowserForm = (DatabaseBrowserForm)ReflectionUtils.newInstance(SpyTabbedBrowserForm.class,
                    new Class<?>[] {com.dci.intellij.dbn.browser.ui.BrowserToolWindowForm.class,
                            com.dci.intellij.dbn.browser.ui.TabbedBrowserForm.class},
                    this, previousTabbedForm);
        } else if (getDisplayMode() == BrowserDisplayMode.SIMPLE) {
            newBrowserForm = (DatabaseBrowserForm)ReflectionUtils.newInstance(SpySimpleBrowserForm.class,
                    new Class<?>[] { com.dci.intellij.dbn.common.dispose.DisposableProjectComponent.class},
                    this);
        }
        setBrowserForm(newBrowserForm);

        JPanel thisBrowserPanel = getBrowserPanel();
        thisBrowserPanel.removeAll();
        thisBrowserPanel.add(getBrowserForm().getComponent(), "Center");
        GUIUtil.repaint(thisBrowserPanel);
        Disposer.register(this, getBrowserForm());
        Disposer.disposeInBackground(new Object[]{oldBrowserForm});
    }

    private JPanel getBrowserPanel() {
        return (JPanel)ReflectionUtils.getFieldValue(this, "browserPanel");
    }

    private void setBrowserForm(DatabaseBrowserForm browserForm) {
        ReflectionUtils.setFieldValue(this, "browserForm", browserForm);
    }
}
